import React, { useEffect, useState } from 'react';
import LoginLog from './login';
import ActionLog from './action';
import LogSet from './logSet'
import { getSystemDisk, batchDeleteLogNew, downloadLogNew } from '~/API/index';
import BreadCrumb from '@/components/BreadCrumb';
import ComfirmDiv from './Compents/comfirm';
import gantan from '@/assets/svg/gantanhao.svg';
import { getParams } from '@/common/constant';
import cn from 'classnames';
import i from '@/index.module.css';
import s from './style.module.less';
import { Tabs, Button, Message, Confirm, Loading, Dialog } from '@knownsec/react-component';
const { TabPane } = Tabs;

export default function LogCenter() {
  const { type, cache_type } = getParams();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState({ threshold: 100, usage: 0 });
  const [needUpdate, setNeedUpdate] = useState(1);
  const [dialogTitle, setDialogTitle] = useState('')
  const [dialogType, setDialogType] = useState('')
  const [visible, setVisible] = useState(false)
  const [cdate, setCdate] = useState(['', ''])
  const [ctype, setCtype] = useState({ operation: true, login: true })
  const exportReport = () => {
    console.log('导出中...');
    comfirmCompent('导出', 'export');
  };
  const delMsgs = () => {
    console.log('删除');
    comfirmCompent('删除', 'del');
  };
  // 设置全局变量
  const setComfirm = (val, type) => {
    if (type === 'date') {
      setCdate(val);
    } else {
      setCtype(Object.assign({}, val));
    }
  };
  const comfirmCompent = (title, type) => {
    setDialogTitle(title)
    setDialogType(type)
    setVisible(true)
  };
  const onSubmit = () => {
    const arr = Object.keys(ctype);
    const logType = arr
      .map((c) => {
        if (ctype[c]) {
          return c;
        } else {
          return '';
        }
      })
      .filter((v) => v);
    if (!logType.length || !cdate || !cdate[0]) {
      Message.show({
        pro: true,
        type: 'warning',
        message: '操作失败，未选择日期或者日志类型',
        showClose: false,
      });
      return;
    }
    if (dialogType === 'del') {
      setLoading(true);
      batchDeleteLogNew({ log_types: logType, start_date: cdate[0], end_date: cdate[1] }).then(
        (res) => {
          setLoading(false);
          setVisible(false)
          if (res.status == 'success') {
            // setSelect([])
            // getData();
            setNeedUpdate(new Date());
            Message.show({
              pro: true,
              type: 'success',
              message: '删除日志成功',
              showClose: false,
            });
          }
        }
      );
    } else {
      downloadLogNew({ log_types: logType, start_date: cdate[0], end_date: cdate[1] });
    }
  }
  const topExport = () => {
    return (
      <div className={s.exportline}>
        <Button className={i.mr20} pro type="primary" onClick={() => exportReport()}>
          导出
        </Button>
        <Button onClick={() => delMsgs()} className={cn(i.mr20, 'delete-btn')} pro type="default">
          删除
        </Button>
      </div>
    );
  };
  const tipWarning = () => {
    let words = '';
    if (data && data.out_memery) {
      data.out_memery.map((item) => {
        if (item.data_usage == 100) {
          words += item.node_ip + '磁盘数据已满，无法存储日志。';
        } else if (item.sys_usage == 100) {
          words += item.node_ip + '系统磁盘已满，无法存储日志。';
        } else if (item.data_usage >= data.threshold) {
          words +=
            item.node_ip +
            '磁盘数据分区空间使用率已达到您设置的告警阀值' +
            data.threshold +
            '%，请您及时处理。';
        } else if (item.sys_usage >= data.threshold) {
          words +=
            item.node_ip +
            '系统磁盘分区空间使用率已达到您设置的告警阀值' +
            data.threshold +
            '%，请您及时处理。';
        }
      });
    }
    if (words) {
      return (
        <div className="warningtip">
          <img src={gantan} alt="" />
          &ensp;{words}
        </div>
      );
    } else {
      return null;
    }
  };
  const getData = () => {
    getSystemDisk().then((res) => {
      if (res.status === 'success') {
        setData(res.data);
      }
    });
  };
  useEffect(() => {
    getData();
  }, []);

  return (
    <div className={i.mainContent}>
      <BreadCrumb arr={[{ link: '', name: '日志中心', active: true }]} />
      <div className={cn(s.content, i.p24, i.oa, i.h100p, i.mins)}>
        <Loading show={loading} />
        <div className={cn(s.bgc, i.df, i.fdc, i.pl20, i.pr20)}>
          <Tabs className={i.flex1} defaultActiveKey={type ? type : 'action'}>
            <TabPane tab="操作日志" key="action">
              {tipWarning()}
              <ActionLog topExport={topExport} updateFlag={needUpdate} />
            </TabPane>
            <TabPane tab="登录日志" key="login">
              {tipWarning()}
              <LoginLog topExport={topExport} updateFlag={needUpdate} />
            </TabPane>
            <TabPane tab="日志设置" key="logSet">
              {tipWarning()}
              <LogSet  />
            </TabPane>
            {/* <TabPane tab="系统日志" key="syslog">
              {topExport()}
              <SysLog />
            </TabPane> */}
          </Tabs>
        </div>
        <Dialog
          className="w540"
          title={dialogTitle + '日志'}
          visible={visible}
          cusCancel={<Button type="default" className={i.mr20} onClick={() => {
            setVisible(false)
            setCdate(['', ''])
            setCtype({ operation: true, login: true })
          }}>取消</Button>}
          onhide={() => {
            setVisible(false)
            setCdate(['', ''])
            setCtype({ operation: true, login: true })
          }} onsubmit={onSubmit}>
          <ComfirmDiv
            key={Math.random().toString(36).slice(-6)}
            title={dialogTitle}
            cdate={cdate}
            ctype={ctype}
            setVal={setComfirm} />
        </Dialog>
      </div>
    </div>
  );
}
